package com.cj.wtrails

import android.Manifest
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.icu.text.IDNA
import android.location.Location
import android.media.Image
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.DisplayMetrics
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.cj.wtrails.adapter.RankingAdapter
import com.cj.wtrails.bean.*
import com.cj.wtrails.fragment.*
import com.cj.wtrails.http.RestClient
import com.cj.wtrails.utils.*
import com.google.gson.Gson
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_tv_main.*
import kotlinx.android.synthetic.main.layout_tv_top.*
import kotlinx.android.synthetic.main.sb_fragment.*
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 *
 * Created by yi on 2020/7/17.
 */
class TvMainActivity : FragmentActivity() {

    var qrImage: Bitmap? = null
    var userInfo: UserInfo? = null
    var dataInfo: DataInfo? = null

    var list: ArrayList<Rank>? = null

    private var rankingAdapter: RankingAdapter? = null

    private val infoFragment by lazy {
        InfoFragment()
    }

    /*private val sbFragment by lazy {
        SbFragment()
    }*/
    var sbFragment: SbFragment? = null

    private val dataFragment by lazy {
        DataFragment()
    }
    private val noDataFragment by lazy {
        NoDataFragment()
    }
    private val successFragment by lazy {
        SuccessFragment()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tv_main)

        //显示屏分辨率
        val displayMetrics = resources.displayMetrics
        tv_dp.text = displayMetrics.toString() + displayMetrics.densityDpi
        tv_dp.isVisible = true
        
        initInfoFragment()
        initView()
        tv_01.setOnClickListener {
            initInfoFragment()
        }
        tv_02.setOnClickListener {
            switchContent(initSbFragment(), "sb")
        }
        tv_03.setOnClickListener {
            initDataFragment()
        }
        tv_04.setOnClickListener {
            initNoFragment()
        }
        tv_05.setOnClickListener {
            initSuccessFragment()
        }
        tv_06.setOnClickListener {
            Toast.makeText(
                this,
                supportFragmentManager.fragments.size.toString(),
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    fun initInfoFragment() {
        switchContent(infoFragment, "info")
    }

    fun initSuccessFragment() {
        switchContent(successFragment, "success")
        if (successFragment.isAdded) {
            successFragment.play()
        }
        getRanks()
    }

    fun initNoFragment() {
        switchContent(noDataFragment, "nodata")
        if (noDataFragment.isAdded) {
            noDataFragment.setText(userInfo)
        }
        getRanks()
    }

    fun initDataFragment() {
        switchContent(dataFragment, "data")
        if (dataFragment.isAdded) {
            dataFragment.setText(dataInfo)
        }
        getRanks()
    }


    private fun initSbFragment(): SbFragment {
        if (sbFragment == null) {
            sbFragment = SbFragment()
        }
        return sbFragment as SbFragment
    }

    override fun onResume() {
        super.onResume()
        CommonUtils.fullScreen(this)
    }

    //防止fragment重叠
    @SuppressLint("MissingSuperCall")
    override fun onSaveInstanceState(outState: Bundle) {
        //super.onSaveInstanceState(outState)
    }

    private fun initView() {
        startAnim()
        //日期
        val date = Date(System.currentTimeMillis())
        val format = SimpleDateFormat("yyyy年MM月dd日 EEEE")
        tv_top_date.text = format.format(date)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)
        rankingAdapter = RankingAdapter()
        recyclerView.adapter = rankingAdapter
        //获取地址
        LocationUtil.getCurrentLocation(this, object : LocationUtil.LocationCallBack {
            override fun onSuccess(location: Location) {
                GetAddressUtil(this@TvMainActivity).getAddress(
                    location.longitude,
                    location.latitude
                )?.let {
                    tv_top_location.text = it
                    weather(it)
                }
            }

            override fun onFail(msg: String) {
                LogUtil.e(msg)
            }
        })
        //获取排行榜
        getRanks()

        //每60s重新请求一遍数据
        Handler().postDelayed({
            getRanks()
        }, 60000)


    }

    private var animator: ValueAnimator? = null
    private fun startAnim() {
        animator = ValueAnimator.ofInt(-2000, 100)
        animator?.duration = 3000
        animator?.repeatCount = -1
        animator?.addUpdateListener { animation ->
            val value = animation.animatedValue as Int
            imageView1.x = value.toFloat() + 600
            imageView1.y = -value.toFloat()

            imageView2.x = value.toFloat() + 1600
            imageView2.y = -value.toFloat()
        }
        animator?.start()

    }

    /**
     * 暂存Fragment
     */
    private var mFragment = Fragment()

    /**
     * 选择Fragment存放
     */
    private fun switchContent(to: Fragment?, tag: String) {

        if (to != null && mFragment !== to) {
            val transaction = supportFragmentManager.beginTransaction()
            // 先判断是否被add过
            if (!to.isAdded) {
                // 隐藏当前的fragment，add下一个到Activity中
                transaction.hide(mFragment).add(R.id.layout_fragment, to, tag)
                    .commitAllowingStateLoss()
            } else {
                // 隐藏当前的fragment，显示下一个
                transaction.hide(mFragment).show(to).commitAllowingStateLoss()
            }
            mFragment = to
        }
    }

    /**获取城市天气*/
    private fun weather(city: String) {
        val url =
            "https://api.seniverse.com/v3/weather/now.json?key=STDVmOktk_4FzD9Hk&location=$city&language=zh-Hans&unit=c"
        RestClient().httpService.weather(url).enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {

            }

            @SuppressLint("SetTextI18n")
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                response.body()?.let {
                    val weather = Gson().fromJson(it.string(), Weather::class.java)
                    LogUtil.e(weather.results[0].now.text)
                    tv_top_weather.text =
                        weather.results[0].now.text + " " + weather.results[0].now.temperature + "℃"
                    //SimpleConfig.setParam(this@TvMainActivity, MyApplication.WEATHER, tv_top_weather.text)
                }

            }
        })
    }


    //获取排行榜数据
    fun getRanks() {
        RestClient().httpService.ranking("0").enqueue(object : Callback<BaseArrayData<Rank>> {
            override fun onFailure(call: Call<BaseArrayData<Rank>>, t: Throwable) {
                t.message?.let { toast(it) }
            }

            override fun onResponse(
                call: Call<BaseArrayData<Rank>>,
                response: Response<BaseArrayData<Rank>>
            ) {
                response.body()?.apply {
                    when (this.status) {
                        200 -> {
                            list = this.data
                            rankingAdapter?.setNewData(this.data)
                            if (infoFragment.isAdded) {
                                infoFragment.setData()
                            }

                        }
                        //  203:no data
                        else -> {
                            rankingAdapter?.setEmptyView(R.layout.layout_empty, recyclerView)
                        }
                    }
                    //initInfoFragment(list)
                }
            }
        })
    }
}